package com.teamAwesome.nfcAlarm;

import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class dbAdapter {

    private SQLiteDatabase mDb;
    private DatabaseHelper mDbHelper;

    private final Context mCtx;

    private final static String TAG = "alarmsDbAdapter";

    private static final String DATABASE_NAME = "nfc_alarms_db";
    private static final String DATABASE_TABLE = "alarms";
    private static final int DATABASE_VERSION = 2;

    /*
     * Column names - id - creation_time - alarm_time - repeat_interval
     */
    private static final String id = "id";
    private static final String creation_time = "creation_time";
    private static final String alarm_time = "alarm_time";
    private static final String repeat_interval = "repeat_interval";

    private static final String DATABASE_CREATE = "create table "
	    + DATABASE_NAME + "(" + id + " integer primary key autoincrement, "
	    + creation_time + " integer not null" + alarm_time
	    + " integer not null" + repeat_interval + " text not null";

    private static class DatabaseHelper extends SQLiteOpenHelper {

	public DatabaseHelper(Context context) {
	    super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

	    db.execSQL(DATABASE_CREATE);

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	    Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
		    + newVersion + ", which will destroy all old data");

	    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

	    onCreate(db);

	}

    }

    public dbAdapter(Context ctx) {
	this.mCtx = ctx;
    }

    public dbAdapter open() throws SQLException {
	mDbHelper = new DatabaseHelper(mCtx);

	mDb = mDbHelper.getWritableDatabase();

	return this;
    }

    public void close() {
	mDbHelper.close();
    }

    public long createAlarm(int alarmTimeStamp, String repeatInterval) {

	ContentValues initialValues = new ContentValues();

	long time = System.currentTimeMillis();

	initialValues.put(creation_time, time);
	initialValues.put(alarm_time, alarmTimeStamp);
	initialValues.put(repeat_interval, repeatInterval);

	return mDb.insert(DATABASE_TABLE, null, initialValues);

    }

}
